﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ControlLib;
using JsonArchive;
using Excel = Microsoft.Office.Interop.Excel;
using System.IO;
using System.Collections;

namespace HousekeepingSystem
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            LoadContractTable();
        }

        private Dictionary<string, object> ContractTable = new Dictionary<string, object>();

        private void LoadContractTable()
        {
            textBox1.SetWatermark("业主电话/合同号");

            String JSON = File.ReadAllText(Application.StartupPath + @"\info\ContractTable.json");
            ContractTable = J2D.JsonToDictionary(JSON);
            SetContractTable();
        }
        private void SetContractTable(string RetrievalStr = "")
        {
            RetrievalStr = RetrievalStr.Trim();
            listView1.BeginUpdate();
            listView1.Items.Clear();
            foreach (var item in ContractTable)
            {
                if (item.Key == "0") continue;
                ListViewItem ContractRow = new ListViewItem();
                ContractRow.Text = item.Key;
                foreach (var data in (ArrayList)item.Value)
                {
                    ContractRow.SubItems.Add(data.ToString());
                }
                listView1.Items.Add(ContractRow);
            }
            for (int i = 0; i < listView1.Items.Count; i++)
            {
                if (listView1.Items[i].SubItems[6].Text == RetrievalStr) continue;
                if (listView1.Items[i].SubItems[12].Text == RetrievalStr) continue;
                if (RetrievalStr == "") continue;
                listView1.Items[i].Remove();
                --i;
            }
            listView1.EndUpdate();
        }

        private void button0_Click(object sender, EventArgs e)
        {
            SetContractTable(textBox1.Text);
            textBox1.Focus();
        }

        //新增合同
        private void button1_Click(object sender, EventArgs e)
        {
            panel1.Focus();
            if (new Form1_1().ShowDialog() == DialogResult.OK)
            {
                textBox1.Text = "";
                LoadContractTable();
            };
        }

        //删除合同
        private void button2_Click(object sender, EventArgs e)
        {
            panel1.Focus();
            if (listView1.CheckedItems.Count < 1) 
            {
                MessageBox.Show("没有被选中的项目！","错误");
                return;
            }
            if(MessageBox.Show("确定要删除选定项?", "警告", MessageBoxButtons.OKCancel) == DialogResult.OK)
            {
                foreach (ListViewItem item in listView1.CheckedItems)
                {
                    ContractTable.Remove(item.Text);
                }
                textBox1.Clear();
                SetContractTable();
                saveContractTable();
            }
        }

        //服务记录
        private void button3_Click(object sender, EventArgs e)
        {
            panel1.Focus();
        }

        //导出表格
        private void button4_Click(object sender, EventArgs e)
        {
            panel1.Focus();
            button4.Enabled = false;
            
            // 创建Excel文档
            Excel.Application ExcelApp = new Excel.Application();
            Excel.Workbook ExcelDoc = ExcelApp.Workbooks.Add(Type.Missing);
            Excel.Worksheet xlSheet = ExcelDoc.Worksheets.Add(Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            ExcelApp.DisplayAlerts = false;
            // 单元格下标是从[1，1]开始的
            Int32 Row = 1;
            Int32 Column = 1;
            //获取表头
            xlSheet.Cells[Row, Column] = "序号";
            for (int i = 1; i < listView1.Columns.Count; i++)
            {
                xlSheet.Cells[Row, Column + i] = listView1.Columns[i].Text;
            }
            //获取内容
            foreach (ListViewItem item in listView1.Items)
            {
                ++Row;
                xlSheet.Cells[Row, Column] = Row - 1;
                for (int i = 1; i < item.SubItems.Count; i++)
                {
                    xlSheet.Cells[Row, Column + i] = item.SubItems[i].Text;
                }
            }
            //自动列宽
            xlSheet.Cells.EntireColumn.AutoFit();

            SaveFileDialog saveFile = new SaveFileDialog();
            saveFile.Title = "保存Excel文件";
            saveFile.Filter = "Excel文件|*.xlsx";
            Boolean FileIsUsed = true;
            while (FileIsUsed)
            {
                if (saveFile.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        if (File.Exists(saveFile.FileName))
                        {
                            File.Move(saveFile.FileName, saveFile.FileName);
                        }
                        FileIsUsed = false;
                    }
                    catch (Exception)
                    {
                        FileIsUsed = true;
                    }
                }
                else
                {
                    break;
                }
                if (FileIsUsed)
                {
                    if (MessageBox.Show("指定文件已被占用，请关闭后重试！", "Error", MessageBoxButtons.RetryCancel) == DialogResult.Cancel)
                    {
                        break;
                    }
                }
                else
                {
                    // 文件保存
                    xlSheet.SaveAs(saveFile.FileName);
                    ExcelDoc.Close(Type.Missing, saveFile.FileName, Type.Missing);
                    ExcelApp.Quit();
                }
            }

            button4.Enabled = true;
        }
        /// <summary>
        /// 保存合同表
        /// </summary>
        private void saveContractTable()
        {
            int listIndex = 0;
            ContractTable.Clear();
            ArrayList ContractRowValue = new ArrayList();
            for (int i = 1; i < listView1.Columns.Count; i++)
            {
                ContractRowValue.Add(listView1.Columns[i].Text);
            }
            ContractTable.Add(listIndex.ToString(), ContractRowValue.ToArray());
            foreach (ListViewItem Item in listView1.Items)
            {
                ContractRowValue.Clear();
                for (int i = 1; i < Item.SubItems.Count; i++)
                {
                    ContractRowValue.Add(Item.SubItems[i].Text);
                }
                ContractTable.Add((++listIndex).ToString(), ContractRowValue.ToArray());
            }
            String JSON = D2J.DictionaryToJson(ContractTable);
            File.WriteAllText(Application.StartupPath + @"\info\ContractTable.json", JSON);
        }

        private void Form1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter && textBox1.Focused)
            {
                this.button0_Click(sender, e);
                e.Handled = true;
            }
            if (e.KeyChar == (char)Keys.Escape)
            {
                if (textBox1.Focused)
                {
                    panel1.Focus();
                    if (textBox1.Text.Trim().Length > 0)
                    {
                        textBox1.Clear();
                        textBox1.Focus();
                        SetContractTable();
                    }
                }
                else
                {
                    this.Close();
                }
                e.Handled = true;
            }
        }
    }
}
